package ui;

import java.util.ArrayList;
import java.util.Date;

import model.Server;
import ListManager.SrcServerListAdapter;
import ListManager.ServerListManager;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.location.Location;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.ui.R;

public class MainActivity extends Activity{
	
	private ImageView scan;
	private TextView serverListText;
	private TextView tapText;
	private ImageView scanAnim;
	private ListView serverListView;
	public static Button nextButton;
	private TextView filterByText;
	private RadioButton filterByName;
	private RadioButton filterByDate;
	private RadioButton filterByDistance;
	
	private MediaPlayer bip = null;
	private AnimationDrawable scanAnimDraw =null;
	private SrcServerListAdapter adapter = null;
	private boolean isFilterName = true;
	private boolean isFilterDistance = false;
	private boolean isFilterDate = false;
	
	public static MainActivity activity;
	private SharedPreferences appSharedPrefs;
	private Editor prefsEditor;
	private Gson gson;
	private String json;
	private Toast toast;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.mainlayout);
		activity = this;
		appSharedPrefs = PreferenceManager.getDefaultSharedPreferences(this.getApplicationContext());
		prefsEditor = appSharedPrefs.edit();
		gson = new Gson();
		
		//View Element
		serverListText=(TextView)findViewById(R.id.serverListText);
		scan= (ImageView)findViewById(R.id.scanBtn);
		tapText = (TextView)findViewById(R.id.tapText);
		scanAnim = (ImageView)findViewById(R.id.scanAnim);
		serverListView = (ListView)findViewById(R.id.serverListView);
		nextButton = (Button) findViewById(R.id.nextButton);
		filterByText = (TextView)findViewById(R.id.filterByTextView);
		filterByName = (RadioButton) findViewById(R.id.filterByNameRadio);
		filterByDate = (RadioButton) findViewById(R.id.filterByDateRadio);
		filterByDistance = (RadioButton) findViewById(R.id.filterByDistanceRadio);
		
		//View Initialisation
		nextButton.setEnabled(false);
		
		//textview font setting
		Typeface font = Typeface.createFromAsset(getAssets(), "font/champ.ttf");
		tapText.setTypeface(font);
		serverListText.setTypeface(font);
		filterByText.setTypeface(font);
		filterByName.setTypeface(font);
		filterByDate.setTypeface(font);
		filterByDistance.setTypeface(font);
		
		//Media player initialisation
		bip = MediaPlayer.create(this, R.raw.bip); 
		
		//Animation Drawable
		scanAnim.setBackgroundResource(R.anim.scan_animation);
		scanAnimDraw = (AnimationDrawable) scanAnim.getBackground();
		scanAnimDraw.start();
		
		//populate server list	
		json = appSharedPrefs.getString("myServerList", "");
		ArrayList<Server> myList = gson.fromJson(json, new TypeToken<ArrayList<Server>>() {}.getType());
		if(myList==null){
			myList = new ArrayList<Server>();
		}
		ServerListManager.getInstance().setServerList(myList);
		adapter = new SrcServerListAdapter(this, ServerListManager.getInstance().getServerList(), getResources());
		serverListView.setAdapter( adapter );
		//TODO hardcode get out
		/*
		for(int i =1;i<20;i++){
			Server s = new Server();
			s.setName("ServerName"+i);
			s.setUrl("http//serverurl"+i);
			Location loc = new Location("");
			loc.setLatitude(Math.random()*100);
			loc.setLongitude(Math.random()*100);
			s.setLocalisation(loc);
			s.setOnline(false);    
			
			Date t = new Date();
			t.setTime((long) (t.getTime()-Math.random()*1000000000));
			s.setLastAccessDate(t);

			ServerListManager.getInstance().addItem(0,s);
		}
		json = gson.toJson(ServerListManager.getInstance().getServerList());
		prefsEditor.putString("myServerList", json);
		prefsEditor.commit(); 
		*/
		
		//scan qr
		scan.setOnTouchListener(new OnTouchListener() {
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				if (event.getAction() == (MotionEvent.ACTION_UP)) {
					scan.setImageResource(R.drawable.boutonout);
					bip.start();
	                Intent intent = new Intent("com.google.zxing.client.android.SCAN");
	                intent.putExtra("SCAN_MODE", "QR_CODE_MODE");
	                startActivityForResult(intent, 0);
				} else if (event.getAction() == (MotionEvent.ACTION_DOWN)) {
					scan.setImageResource(R.drawable.boutonin);
					
				}
				return true;
			}
		});
		
		filterByName.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					adapter.setSelectedItem(-1);
					nextButton.setEnabled(false);
					isFilterName=true;
					isFilterDate=false;
					isFilterDistance=false;
					filterByDate.setChecked(false);
					filterByDistance.setChecked(false);
					ServerListManager.getInstance().orderListBy("name");
					adapter.notifyDataSetChanged();
				}
			}
		});
		filterByName.setChecked(true);
		
		filterByDate.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					adapter.setSelectedItem(-1);
					nextButton.setEnabled(false);
					isFilterName=false;
					isFilterDate=true;
					isFilterDistance=false;
					filterByName.setChecked(false);
					filterByDistance.setChecked(false);
					ServerListManager.getInstance().orderListBy("date");
					adapter.notifyDataSetChanged();
				}
			}
		});
		
		filterByDistance.setOnCheckedChangeListener(new OnCheckedChangeListener() {
			@Override
			public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
				if(isChecked){
					adapter.setSelectedItem(-1);
					nextButton.setEnabled(false);
					isFilterName=false;
					isFilterDate=false;
					isFilterDistance=true;
					filterByDate.setChecked(false);
					filterByName.setChecked(false);
					ServerListManager.getInstance().orderListBy("distance");
					adapter.notifyDataSetChanged();
				}
			}
		});
		
		nextButton.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent myIntent = new Intent(MainActivity.activity, FileListActivity.class);
				myIntent.putExtra("position", adapter.getSelectedItem());
				startActivity(myIntent);      
                finish();
			}
		});
	}
	
    @Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflator=new MenuInflater(this);
		inflator.inflate(R.layout.pref_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch (item.getItemId()) {
			case R.id.MENU_PREF:
		}
		return super.onOptionsItemSelected(item);
	}
	
	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent intent) {
	    if (requestCode == 0) {	 
	    	//Toast
	    	LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.layout.toast_layout,
			                               (ViewGroup) findViewById(R.id.toast_layout_root));

			Typeface font = Typeface.createFromAsset(getAssets(), "font/champ.ttf");
			TextView text = (TextView) layout.findViewById(R.id.toastText);
			text.setTypeface(font);
			LinearLayout ll = (LinearLayout)layout.findViewById(R.id.toast_layout_root);
			ImageView iv = (ImageView)layout.findViewById(R.id.toastImage);
			iv.setImageDrawable(getResources().getDrawable(R.drawable.scan_android_icon));
			
	        if (resultCode == RESULT_OK) {
	            String contents = intent.getStringExtra("SCAN_RESULT");
	            String format = intent.getStringExtra("SCAN_RESULT_FORMAT");  
	            Log.d("content", contents);
	            Log.d("format", format);
	            
	            //TODO when qr generator is done server side
	            String[] contentArray = contents.split(";");
	            Server newServer = new Server();
	            newServer.setName(contentArray[0]);
	            newServer.setUrl(contentArray[1]);
	            Location l = new Location("");
	            l.setLatitude(Integer.parseInt(contentArray[2]));
	            l.setLongitude(Integer.parseInt(contentArray[3]));
	            newServer.setLocalisation(l);
	            newServer.setOnline(true);
	            newServer.setLastAccessDate(new Date());
	            
	            ServerListManager.getInstance().addItem(0, newServer);
	    		json = gson.toJson(ServerListManager.getInstance().getServerList());
	    		prefsEditor.putString("myServerList", json);
	    		prefsEditor.commit(); 
	    		
	            if(isFilterName){
	            	filterByName.setChecked(false);
	            	filterByName.setChecked(true);
	            }
	            else if(isFilterDistance){
	            	filterByDistance.setChecked(false);
	            	filterByDistance.setChecked(true);
	            }
	            else if(isFilterDate){
	            	filterByDate.setChecked(false);
	            	filterByDate.setChecked(true);
	            }
	            
	            //toast show
	            text.setText(getResources().getString(R.string.validScan));
	            ll.setBackgroundColor(getResources().getColor(R.color.greenAlpha));
	            if(toast!=null){
					toast.cancel();
				}
				toast = new Toast(getApplicationContext());
				toast.setGravity(Gravity.TOP|Gravity.RIGHT, 130, 50);
				toast.setDuration(Toast.LENGTH_SHORT);
				toast.setView(layout);
				toast.show();
	            
	        } else if (resultCode == RESULT_CANCELED) {
	            //toast show
	            text.setText(getResources().getString(R.string.cancelScan));
	            ll.setBackgroundColor(getResources().getColor(R.color.redAlpha));
	            if(toast!=null){
					toast.cancel();
				}
				toast = new Toast(getApplicationContext());
				toast.setGravity(Gravity.TOP|Gravity.RIGHT, 130, 50);
				toast.setDuration(Toast.LENGTH_SHORT);
				toast.setView(layout);
				toast.show();
	        }
	   }
	}
	
	public void onServerItemClick(int mPosition){        
		if(ServerListManager.getInstance().getServerList().get(mPosition).isOnline()){
			nextButton.setEnabled(true);
		}
		else{
			nextButton.setEnabled(false);
		}
	}
	
	public void onServerItemLongClick(int mPosition){
		if(ServerListManager.getInstance().getServerList().size()>0){
			ServerListManager.getInstance().removeItem(mPosition);
			json = gson.toJson(ServerListManager.getInstance().getServerList());
			prefsEditor.putString("myServerList", json);
			prefsEditor.commit(); 
			
			LayoutInflater inflater = getLayoutInflater();
			View layout = inflater.inflate(R.layout.toast_layout,
			                               (ViewGroup) findViewById(R.id.toast_layout_root));

			Typeface font = Typeface.createFromAsset(getAssets(), "font/champ.ttf");
			TextView text = (TextView) layout.findViewById(R.id.toastText);
			text.setTypeface(font);
			text.setText(getResources().getString(R.string.toastText));
			LinearLayout ll = (LinearLayout)layout.findViewById(R.id.toast_layout_root);
			ll.setBackgroundColor(getResources().getColor(R.color.redAlpha));
			ImageView iv = (ImageView)layout.findViewById(R.id.toastImage);
			iv.setImageDrawable(getResources().getDrawable(R.drawable.delete));
			
			if(toast!=null){
				toast.cancel();
			}
			toast = new Toast(getApplicationContext());
			toast.setGravity(Gravity.TOP|Gravity.RIGHT, 130, 50);
			toast.setDuration(Toast.LENGTH_SHORT);
			toast.setView(layout);
			toast.show();
		}
	}
	
	@Override
    public void onResume() {
        super.onResume();        
    }
	
	@Override
    public void onPause() {
        super.onPause();
    }
    
	@Override
	protected void onDestroy() {
		super.onDestroy();	
	}
	
}
